#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/10/7 18:26
# @Author  : AshJo
# @Desc    : 互斥锁
# @Filename: lock.py
# @Version : v1.0
"""
import json
import time
from multiprocessing import Process, Lock


def search(i):
    with open('ticket', encoding='utf-8') as f:
        ticket = json.load(f)
    print('%s 当前剩余车票%s张' % (i, ticket['count']))


def buy(i):
    with open('ticket', encoding='utf-8') as f:
        ticket = json.load(f)
    if ticket['count'] > 0:
        ticket['count'] -= 1
        print('%s号买到车票了！' % (i))
    time.sleep(0.5)
    with open('ticket', encoding='utf-8', mode='w') as f:
        json.dump(ticket, f)


def get_ticket(i, lock):
    search(i)
    with lock:
        buy(i)


if __name__ == '__main__':
    lock = Lock()
    for i in range(15):
        Process(target=get_ticket, args=(i, lock)).start()
